import { getUserPermission, login } from "@/request/api";
import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const userPermissionStore = defineStore("userPermission", () => {
  const userInfo = ref({});
  const menuData = ref([]);
  const permissions = ref([]);
  
  function Login(params) {
    return new Promise((resolve, reject) => {
      login(params).then((res) => {
        userInfo.value = res.userInfo;
        localStorage.setItem("token", res.token);
        resolve(res);
      });
    });
  }
  
  function getUserPermissionInfo() {
    return new Promise((resolve, reject) => {
      getUserPermission().then((res) => {
        if (res.code === 200 && res.data) {
          menuData.value = res.data.menus || [];
          permissions.value = res.data.permissions || [];
          resolve(res);
        } else {
          console.error('获取权限数据失败:', res);
          menuData.value = [];
          permissions.value = [];
          reject(new Error('获取权限数据失败'));
        }
      }).catch(error => {
        console.error('获取权限请求失败:', error);
        menuData.value = [];
        permissions.value = [];
        reject(error);
      });
    });
  }
  
  // 检查是否有某个权限
  const hasPermission = computed(() => {
    return (permissionCode) => {
      if (!permissionCode) return true;
      return permissions.value.includes(permissionCode);
    };
  });

  return { 
    Login, 
    menuData, 
    permissions,
    getUserPermissionInfo,
    hasPermission
  };
});
